﻿using Aliyun.OSS;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Web;
using utils.EX;

/// <summary>
/// 图片上传工具类
/// </summary>
public class FileHelper
{
    private static string endpoint = "oss-cn-guangzhou.aliyuncs.com";//OSS访问域名 
    private static string accessKeyId = "LTAI5tKGXynp3AYZhsUyqMvb";//OSS密钥
    private static string accessKeySecret = "ECSWO51DwyAX9aOiBvNM8Vi4kaDwgk";//OSS密钥
    private static string returnUrl = "https://resourcesza.oss-cn-guangzhou.aliyuncs.com/";//上传返回地址
    private static string bucketName = "resourcesza";//存储空间

    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="file">文件</param>
    /// <param name="fileRename">文件后缀</param>
    /// <param name="newFileName">新文件名</param>
    /// <returns></returns>
    public static string UpToAliYunImgage(IFormFile file, string fileRename,string newFileName)
    {
        using (Stream stream= file.OpenReadStream())
        {
            if (stream == null)
            {
                throw new MyException(403, "请选择要上传的文件");
            }
            //获取文件后缀名
            //string fileRename = Path.GetExtension(file.FileName);

            //文件名
            string fileName = "portraits/" + newFileName;
            OssClient oss = new OssClient(endpoint, accessKeyId, accessKeySecret);
            stream.Position = 0;
            oss.PutObject(bucketName, fileName, stream);
            //stream.Dispose();//释放文件流
            return returnUrl + fileName;
        }
      
    }

    /// <summary>
    /// 生成随机文件名
    /// </summary>
    /// <param name="currentPhotoPath"></param>
    /// <returns></returns>
    public static string PhotoSave(string currentPhotoPath)
    {
        //随机生成图片的名称(14位日期加上2位随机值+后缀名)
        string PhotoName = DateTime.Now.ToString("yyyyMMddHHmmss");
        //加上两位的随机值
        Random objRandm = new Random();//实例化随机的方法
        PhotoName += objRandm.Next(0, 100).ToString("00");
        //加上文件的后缀名称
        PhotoName += currentPhotoPath.Substring(currentPhotoPath.Length - 4);
        //生成完整的据对路径
        //PhotoName = @"portraits/" + PhotoName;
        return PhotoName;
    }

    /// <summary>
    /// 访问地址
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static string PhotoUrl(string fileName)
    {
        return returnUrl+ "portraits/"+ fileName;
    }
}
